package com.pid.web.controller.system;

import java.util.List;
import java.util.stream.Collectors;

import com.pid.common.constant.CustomerConstants;
import com.pid.common.core.domain.entity.SysRole;
import com.pid.common.core.domain.entity.SysUser;
import com.pid.common.utils.StringUtils;
import com.pid.system.service.ISysRoleService;
import com.pid.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.pid.common.annotation.Log;
import com.pid.common.core.controller.BaseController;
import com.pid.common.core.domain.AjaxResult;
import com.pid.common.enums.BusinessType;
import com.pid.system.domain.SysCustomer;
import com.pid.system.service.ISysCustomerService;
import com.pid.common.utils.poi.ExcelUtil;
import com.pid.common.core.page.TableDataInfo;

import static com.pid.common.utils.spring.SpringUtils.getType;

/**
 * 客户列表Controller
 * 
 * @author pid
 * @date 2021-11-16
 */
@RestController
@RequestMapping("/system/customer")
public class SysCustomerController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysCustomerService sysCustomerService;

    /**
     * 查询客户列表
     */
    @PreAuthorize("@ss.hasPermi('system:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysCustomer sysCustomer)
    {
        startPage();
        List<SysCustomer> list = sysCustomerService.selectSysCustomerList(sysCustomer);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('system:customer:list')")
    @GetMapping("/selectuserbyid/{customerId}")
    public AjaxResult Customer(@PathVariable(value = "customerId",required = false) Long id)
    {
        AjaxResult ajax = AjaxResult.success();
        SysCustomer customer = sysCustomerService.selectSysCustomerByCustomerId(id);
        ajax.put(AjaxResult.DATA_TAG, customer);
        return ajax;
    }

    /**
     * 导出客户列表
     */
    @PreAuthorize("@ss.hasPermi('system:customer:export')")
    @Log(title = "客户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysCustomer sysCustomer)
    {
        List<SysCustomer> list = sysCustomerService.selectSysCustomerList(sysCustomer);
        ExcelUtil<SysCustomer> util = new ExcelUtil<SysCustomer>(SysCustomer.class);
        return util.exportExcel(list, "客户数据");
    }

    /**
     * 获取客户详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:customer:query')")
    @GetMapping(value = {"/","/{customerId}/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "customerId",required = false) Long customerId,
                               @PathVariable(value = "userId",required = false) Long userId)
    {
        //加入该行的作用为利用aop代理类带检查当前登录的角色是否有  增加/删除/更新  当前列表的权限。
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(customerId) && StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, sysCustomerService.selectSysCustomerByCustomerId(customerId));
        }
        return ajax;
    }

//    /**
//     * 获取客户详细信息ByuserId
//     */
//    @PreAuthorize("@ss.hasPermi('system:customer:query')")
//    @GetMapping("/getCustomerByuserId")
//    public String getCustomerByuserId(@RequestParam Long customerId,@RequestParam Long userId)
//    {
//        System.out.println(customerId+"------"+userId);
//        return "success";
//    }

    /**
     * 新增客户
     */
    @PreAuthorize("@ss.hasPermi('system:customer:add')")
    @Log(title = "客户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysCustomer sysCustomer)
    {
        if (CustomerConstants.NOT_UNIQUE.equals(sysCustomerService.checkUnitNameUnique(sysCustomer.getUnitName())))
        {
            return AjaxResult.error("新增客户'" + sysCustomer.getUnitName() + "'失败，该客户已存在");
        }
        else if (StringUtils.isNotEmpty(sysCustomer.getContactNumber())
                && CustomerConstants.NOT_UNIQUE.equals(sysCustomerService.checkPhoneUnique(sysCustomer)))
        {
            return AjaxResult.error("新增客户'" + sysCustomer.getUnitName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(sysCustomer.getEmail())
                && CustomerConstants.NOT_UNIQUE.equals(sysCustomerService.checkEmailUnique(sysCustomer)))
        {
            return AjaxResult.error("新增用户'" + sysCustomer.getUnitName() + "'失败，邮箱账号已存在");
        }
        return toAjax(sysCustomerService.insertSysCustomer(sysCustomer));
    }

    /**
     * 修改客户
     */
    @PreAuthorize("@ss.hasPermi('system:customer:edit')")
    @Log(title = "客户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysCustomer sysCustomer)
    {
        return toAjax(sysCustomerService.updateSysCustomer(sysCustomer));
    }

    /**
     * 删除客户
     */
    @PreAuthorize("@ss.hasPermi('system:customer:remove')")
    @Log(title = "客户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds)
    {
        return toAjax(sysCustomerService.deleteSysCustomerByCustomerIds(customerIds));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:customer:edit')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user,@RequestBody SysCustomer customer)
    {
        user.setUpdateBy(getUsername());
        return toAjax(sysCustomerService.updateCustomerStatus(customer));
    }
}
